using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using NetWing.BPM.Admin.JydflowTasktemplate;

namespace NetWing.BPM.Admin.Jydflowtasklist.ashx
{
    /// <summary>
    /// 任务列表 的摘要说明
    /// </summary>
    public class JydflowtasklistHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<JydflowtasklistModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<JydflowtasklistModel>>(json);
                rpm.CurrentContext = context;
            }
            if (string.IsNullOrEmpty(rpm.Action))
            {
                rpm.Action = context.Request["action"];
            }


            switch (rpm.Action)
            {
                #region  PC执行处理
                case "handlee":
                    string keyidy = context.Request["KeyID"];
                    string orderid = context.Request["orderID"];
                    DataRow 吃 = SqlEasy.ExecuteDataRow("select * from jydflowtasklist where orderid='" + orderid + "'");//查出当前orderid的当前执行序号
                    //查出当前执行序号最大数
                    int 了 = Convert.ToInt32(SqlEasy.ExecuteScalar("select max(sortid) from jydflowTasktemplate where PrintedmatterID='" + 吃["PrintedmatterID"].ToString() + "'"));
                    if (吃["isitcomplete"].ToString() == "0")
                    {
                        context.Response.Write("{\"status\":\"0\",\"filename\":\"此订单已完成\"}");
                    }
                    else
                    {
                        try
                        {

                            if (了 != int.Parse(吃["isitcomplete"].ToString()))
                            {
                                //获取当前执行序号 + 1
                                int a = int.Parse(吃["isitcomplete"].ToString()) + 1;
                                //查出+1之后的执行序号
                                DataTable arrayia;
                                DataRow 饭 = SqlEasy.ExecuteDataRow("select * from jydflowTasktemplate where sortid='" + a + "' and Printedmattername='" + 吃["Printedmattername"].ToString() + "'");
                                DataRow 头晕 = SqlEasy.ExecuteDataRow("select * from jydflowTasktemplate where sortid='" + 吃["isitcomplete"].ToString() + "'");
                                SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                                JydflowRecordModel jydflowRecordModel = new JydflowRecordModel
                                {
                                    processID = int.Parse(头晕["KeyId"].ToString()),
                                    Operationalcontent = 头晕["nodename"].ToString(),
                                    Operationtime = DateTime.Now,
                                    Operctionname = SysVisitor.Instance.cookiesUserName,
                                    orderid = orderid,
                                    Remarks = SysVisitor.Instance.cookiesUserName + "在后台操作",
                                    nikeyid = int.Parse(吃["orderkey"].ToString())


                                };
                                DbUtils.tranInsert(jydflowRecordModel, tran);//提交流程操作记录
                                tran.Commit();//提交事务
                                //修改当前orderid的执行序号
                                int 好 = SqlEasy.ExecuteNonQuery("update jydflowtasklist set isitcomplete='" + 饭["sortid"].ToString() + "',nodename='" + 饭["nodename"].ToString() + "',operatorID='" + 饭["operatorID"].ToString() + "',operatorname='" + 饭["operatorname"].ToString() + "' where orderid='" + orderid + "'");
                                if (好 == 1)
                                {
                                    //开始发送微信
                                    try
                                    {

                                        var templateData = new ProductTemplateData()
                                        {
                                            first = new TemplateDataItem(吃["ordername"].ToString() + "通知", "#000000"),
                                            keyword1 = new TemplateDataItem("JYD" + 吃["orderid"].ToString(), "#000000"),
                                            keyword2 = new TemplateDataItem(SysVisitor.Instance.cookiesUserName + "已处理" + 吃["nodename"].ToString() + "。你要完成" + 饭["nodename"].ToString(), "#000000"),
                                            keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd")),
                                            keyword4 = new TemplateDataItem(吃["nodename"].ToString(), "#000000"),
                                            keyword5 = new TemplateDataItem(吃["nodename"].ToString(), "#000000"),
                                            remark = new TemplateDataItem("此任务中你所做操作<" + 饭["nodename"].ToString() + ">,请尽快完成!备注:", "#66ccff")
                                        };
                                        string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                                               //通知所有员工就是openid不同
                                        string str = 饭["operatorname"].ToString();
                                        string[] arraya = str.Split(',');
                                        foreach (string i in arraya)
                                        {
                                            arrayia = SqlEasy.ExecuteDataTable("select * from sys_users where username='" + i.ToString() + "'");


                                            foreach (DataRow adata in arrayia.Rows)
                                            {
                                                string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(adata["openid"].ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + 吃["keyid"].ToString() + "", templateData);
                                            }
                                        }
                                    }
                                    catch (Exception s)
                                    {
                                        WriteLogs.WriteLogsE("Logs", "Error >> xiugai", s.Message + " >>> " + s.StackTrace);
                                    }
                                }
                                context.Response.Write("{\"status\":\"1\",\"filename\":\"处理成功\"}");
                            }
                            else
                            {
                                int 头疼 = SqlEasy.ExecuteNonQuery("update jydflowtasklist set isitcomplete=0 where orderid='" + orderid + "'");
                                context.Response.Write("{\"status\":\"1\",\"filename\":\"完成了\"}");
                            }
                        }
                        catch (Exception e)
                        {
                            WriteLogs.WriteLogsE("Logs", "Error >> xiugai", e.Message + " >>> " + e.StackTrace);
                        }
                    }
                    break;
                #endregion

                #region 查看详细任务
                case "mobileViewFlowDit"://查看流程明细
                    try
                    {
                        string akeyid = context.Request["keyid"];//子订单ID
                        string vsql = "select top 1 * from jydOrderDetail where  KeyId =" + akeyid + "";
                        DataRow dr2o = SqlEasy.ExecuteDataRow(vsql);//查出订单相关
                        string dt1o = "select * from jydflowtasklist where schemecontent='" + akeyid + "'";
                        //DataRow row1o = SqlEasy.ExecuteDataRow(dt1o);

                        //"select * from jydOrder where orderid='" + row1o["orderid"].ToString() + "'"
                        SqlDataReader vdr = SqlEasy.ExecuteDataReader(dt1o);
                        JydflowtasklistModel fimm = new JydflowtasklistModel();
                        while (vdr.Read())
                        {
                            fimm.InjectFrom<ReaderInjection>(vdr);
                        }
                        string fohsql = "select * from jydflowRecord where schemecontent=" + akeyid + " order by keyid asc";
                        DataTable fhodt = SqlEasy.ExecuteDataTable(fohsql);
                        context.Response.Write(JSONhelper.ToJson(fhodt));
                    }
                    catch (Exception e)
                    {
                        WriteLogs.WriteLogsE("Logs", "Error >> xiugai", e.Message + " >>> " + e.StackTrace);
                    }
                    break;
                #endregion

                #region 任务处理
                case "doflow":
                    string VerificationOpinion = context.Request["VerificationOpinion"];//备注
                    string FlowInstanceId = context.Request["FlowInstanceId"];//节点ID
                    string VerificationFinally = context.Request["VerificationFinally"];//结果
                    string sl = context.Request["sl"];
                    string keyid = context.Request["keyid"];//keyid
                    string dr1 = "select top 1 * from jydOrderDetail where KeyId =" + keyid + "";
                    string username = context.Request["username"];
                    #region 不选择流程

                    if (username == "0")
                    {
                        DataRow dr2 = SqlEasy.ExecuteDataRow(dr1);//查出订单相关
                        string dt1 = "select * from jydflowtasklist where orderID='" + dr2["OrderID"].ToString() + "'";


                        DataRow row = SqlEasy.ExecuteDataRow(dt1);//查出任务相关类型
                        string xg = "select max(sortid) from jydflowTasktemplate where Printedmattername='" + row["Printedmattername"].ToString() + "'";
                        int xgzxs = (Int32)SqlEasy.ExecuteScalar(xg);//查出任务模板排序最大数量
                        string ccpxs = "select * from jydflowTasktemplate where keyid=" + FlowInstanceId + "";
                        DataRow dataRow1 = SqlEasy.ExecuteDataRow(ccpxs);//查出模板排序数字
                        DataRow data = SqlEasy.ExecuteDataRow("select * from jydOrder where OrderID='" + dr2["orderid"].ToString() + "'");
                        string myopid = CookieHelper.GetCookie("openid");
                        DataRow rowuser = SqlEasy.ExecuteDataRow("select * from sys_users where openid='" + myopid + "'");
                        string openid = CookieHelper.GetCookie("useropenid");//获取当前用户openID
                        DataRow openidrow = SqlEasy.ExecuteDataRow("select * from Sys_Users where openid='" + openid + "'");
                        DataTable arrayi;
                        //object objjj = null;
                        if (int.Parse(row["isitcomplete"].ToString()) != 0) //看这个订单是否已经完成了
                        {
                            try
                            {
                                if (VerificationFinally == "1")//操作处理状态必须是1
                                {

                                    if (Convert.ToInt32(row["isitcomplete"].ToString()) == xgzxs)//如果任务表的执行数字与任务模板排序最大数相同,就完成
                                    {
                                        int wanc = SqlEasy.ExecuteNonQuery("update jydflowtasklist set isitcomplete=0 where schemecontent='" + keyid + "'");
                                        context.Response.Write("{\"status\":\"0\",\"filename\":\"订单已完成\"}");
                                    }
                                    else
                                    {
                                        #region MyRegion
                                        int iCode = 0;
                                        int i = Convert.ToInt32(dataRow1["sortid"].ToString());//当前执行序号
                                        string dt2 = "select * from jydflowTasktemplate where sortid='" + i + "' and Printedmattername='" + row["Printedmattername"].ToString() + "'";
                                        DataRow row1 = SqlEasy.ExecuteDataRow(dt2);//当前任务相关人员-操作
                                        int iI = i + 1;
                                        string dt3 = "select * from jydflowTasktemplate where sortid='" + iI + "' and Printedmattername='" + row["Printedmattername"].ToString() + "'";
                                        DataRow row2 = SqlEasy.ExecuteDataRow(dt3);//下级任务相关人员-通知
                                        if (int.Parse(row2["nodetype"].ToString()) == 1)
                                        {
                                            if (row2["nodename"].ToString() == "腹膜" && string.IsNullOrEmpty(dr2["fumoa"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["tana"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["uva"].ToString()))
                                                    {
                                                        iI++;
                                                        if (string.IsNullOrEmpty(dr2["db"].ToString()))
                                                        {
                                                            iI++;
                                                            if (string.IsNullOrEmpty(dr2["zheye"].ToString()))
                                                            {
                                                                iI++;
                                                                if (string.IsNullOrEmpty(dr2["zd"].ToString()))
                                                                {
                                                                    iI++;
                                                                    if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                                    {
                                                                        iI++;
                                                                        if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                                        {
                                                                            iI++;

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "烫" && string.IsNullOrEmpty(dr2["tana"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["uva"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["db"].ToString()))
                                                    {
                                                        iI++;
                                                        if (string.IsNullOrEmpty(dr2["zheye"].ToString()))
                                                        {
                                                            iI++;
                                                            if (string.IsNullOrEmpty(dr2["zd"].ToString()))
                                                            {
                                                                iI++;
                                                                if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                                {
                                                                    iI++;
                                                                    if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                                    {
                                                                        iI++;

                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "uv" && string.IsNullOrEmpty(dr2["uva"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["db"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["zheye"].ToString()))
                                                    {
                                                        iI++;
                                                        if (string.IsNullOrEmpty(dr2["zd"].ToString()))
                                                        {
                                                            iI++;
                                                            if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                            {
                                                                iI++;
                                                                if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                                {
                                                                    iI++;

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "模切" && string.IsNullOrEmpty(dr2["db"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["zheye"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["zd"].ToString()))
                                                    {
                                                        iI++;
                                                        if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                        {
                                                            iI++;
                                                            if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                            {
                                                                iI++;

                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "折页" && string.IsNullOrEmpty(dr2["zheye"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["zd"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                    {
                                                        iI++;
                                                        if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                        {
                                                            iI++;

                                                        }
                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "装订" && string.IsNullOrEmpty(dr2["zd"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["bh"].ToString()))
                                                {
                                                    iI++;
                                                    if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                    {
                                                        iI++;

                                                    }
                                                }
                                            }
                                            if (row2["nodename"].ToString() == "裱盒" && string.IsNullOrEmpty(dr2["bh"].ToString()))
                                            {
                                                iI++;
                                                if (string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                                {
                                                    iI++;

                                                }
                                            }
                                            if (row2["nodename"].ToString() == "压型" && string.IsNullOrEmpty(dr2["yaa"].ToString()))
                                            {
                                                iI++;

                                            }

                                        }
                                        dt3 = "select * from jydflowTasktemplate where sortid='" + iI + "' and Printedmattername='" + row["Printedmattername"].ToString() + "'";
                                        row2 = SqlEasy.ExecuteDataRow(dt3);//下级任务相关人员-通知-再次赋值
                                        DataTable dt = SqlEasy.ExecuteDataTable("select username,openid from sys_users");


                                        Dictionary<string, string> di = new Dictionary<string, string>();
                                        foreach (DataRow dru in dt.Rows)
                                        {
                                            if (!string.IsNullOrEmpty(dru["openid"].ToString()) && !di.ContainsKey(dru["username"].ToString()))
                                                di.Add(dru["username"].ToString(), dru["openid"].ToString());
                                        }
                                        string str = row1["operatorname"].ToString();
                                        string[] arraya = str.Split(',');
                                        foreach (string ai in arraya)
                                        {
                                            if (!string.IsNullOrEmpty(ai))
                                            {
                                                if (openid == di[ai])
                                                {
                                                    SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                                                    DbUtils.tranExecuteNonQuery("update jydflowtasklist set isitcomplete=" + iI + ",nodename = '" + dataRow1["nodename"].ToString() + "',operatorID='" + dataRow1["operatorID"].ToString() + "',operatorname = '" + dataRow1["operatorname"].ToString() + "',completeofth=completeofth+'," + VerificationOpinion + ":" + sl + "' where schemecontent='" + keyid + "'", tran);
                                                    JydflowRecordModel jydflowRecordModel = new JydflowRecordModel
                                                    {
                                                        processID = Convert.ToInt32(FlowInstanceId),
                                                        Operationalcontent = dataRow1["nodename"].ToString(),
                                                        Operationtime = DateTime.Now,
                                                        addtime = row["timestamp"].ToString(),
                                                        Operctionname = openidrow["UserName"].ToString(),
                                                        orderid = dr2["orderid"].ToString(),
                                                        Remarks = VerificationOpinion,
                                                        nikeyid = int.Parse(row["orderkey"].ToString()),
                                                        sortid = int.Parse(dataRow1["sortid"].ToString()),
                                                        sl = int.Parse(sl),
                                                        SchemeContent = int.Parse(keyid)
                                                    };
                                                    DbUtils.tranInsert(jydflowRecordModel, tran);//提交流程操作记录
                                                    try


                                                    {
                                                        tran.Commit();
                                                        iCode = 1;
                                                        string str2 = row2["operatorname"].ToString();
                                                        string[] arraya2 = str2.Split(',');
                                                        foreach (string ai2 in arraya2)
                                                        {
                                                            if (di.ContainsKey(ai2))
                                                            {
                                                                //为模版中的各属性赋值
                                                                var templateData = new ProductTemplateData()
                                                                {
                                                                    first = new TemplateDataItem(row["ordername"].ToString() + "通知", "#66ccff"),
                                                                    keyword1 = new TemplateDataItem("JYD" + row["orderid"].ToString(), "#66ccff"),
                                                                    keyword2 = new TemplateDataItem(openidrow["UserName"].ToString() + "已完成" + dataRow1["nodename"].ToString() + "。你要完成" + row2["nodename"].ToString(), "#66ccff"),
                                                                    keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"), "#66ccff"),
                                                                    keyword4 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#66ccff"),
                                                                    keyword5 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#66ccff"),
                                                                    remark = new TemplateDataItem("此任务中你所做操作<" + row2["nodename"].ToString() + ">,请尽快完成!备注:" + VerificationOpinion, "#66ccff")
                                                                };
                                                                string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                                                                       //通知所有员工就是openid不同
                                                                string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(di[ai2], templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + data["keyid"].ToString() + "", templateData);
                                                            }
                                                        }



                                                    }
                                                    catch
                                                    {
                                                        tran.Rollback();
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (iCode > 0)
                                            context.Response.Write("{\"status\":\"1\",\"filename\":\"修改成功\"}");
                                        else
                                            context.Response.Write("{\"status\":\"2\",\"filename\":\"openid不匹配\"}");
                                        return;
                                        #endregion

                                    }


                                }
                                else if (VerificationFinally == "2")
                                {

                                    int i2 = Convert.ToInt32(dataRow1["sortid"].ToString()) - 1;
                                    //减去当前排序数1,得到上一位执行者
                                    //string openid = CookieHelper.GetCookie("useropenid");//获取当前用户openID
                                    //DataRow openidrow = SqlEasy.ExecuteDataRow("select * from Sys_Users where openid='" + openid + "'");
                                    //数据库中数据已改变,在这里需要重新查一次数据发送微信
                                    string dt2 = "select * from jydflowTasktemplate where sortid='" + i2 + "' and Printedmattername='" + row["Printedmattername"].ToString() + "'";
                                    DataRow row1 = SqlEasy.ExecuteDataRow(dt2);//查出任务相关类型
                                                                               //因为要重做,所以要将任务列表中的当前在做-1
                                    int chongzuo = Convert.ToInt32(SqlEasy.ExecuteScalar("update jydflowtasklist set isitcomplete=isitcomplete" + -1 + " where schemecontent='" + keyid + "'"));

                                    try
                                    {
                                        string str = row1["operatorname"].ToString();
                                        string[] arraya = str.Split(',');
                                        foreach (string ai in arraya)
                                        {
                                            arrayi = SqlEasy.ExecuteDataTable("select * from sys_users where username='" + ai.ToString() + "'");


                                            foreach (DataRow adata in arrayi.Rows)
                                            {
                                                //为模版中的各属性赋值
                                                var templateData = new ProductTemplateData()
                                                {
                                                    first = new TemplateDataItem(row["ordername"].ToString() + "通知", "#e51d36"),
                                                    keyword1 = new TemplateDataItem("JYD" + row["orderid"].ToString(), "#e51d36"),
                                                    keyword2 = new TemplateDataItem(row1["nodename"].ToString() + "完成被驳回。", "#e51d36"),
                                                    keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"), "#e51d36"),
                                                    keyword4 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#e51d36"),
                                                    keyword5 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#e51d36"),
                                                    remark = new TemplateDataItem("此任务中你要重做操作<" + row1["nodename"].ToString() + ">,请尽快完成!备注:" + VerificationOpinion, "#e51d36")
                                                };
                                                string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                                                       //通知所有员工就是openid不同
                                                string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(adata["openid"].ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + data["keyid"].ToString() + "", templateData);
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        context.Response.Write("{\"status\":\"2\",\"filename\":\"'" + e.Message + "'\"}");//发送微信出错
                                        WriteLogs.WriteLogsE("Logs", "Error >> 发送微信", e.Message + " >>> " + e.StackTrace);
                                    }


                                    context.Response.Write("{\"status\":\"1\",\"filename\":\"修改成功\"}");//修改成功

                                }
                                else
                                {
                                    DataTable hggly = SqlEasy.ExecuteDataTable("select * from sys_users where Remark='工厂主管'");
                                    foreach (DataRow adataRow in hggly.Rows)
                                    {
                                        //为模版中的各属性赋值
                                        var templateData = new ProductTemplateData()
                                        {
                                            first = new TemplateDataItem(row["ordername"].ToString() + "通知", "#e51d36"),
                                            keyword1 = new TemplateDataItem("JYD" + row["orderid"].ToString(), "#000000"),
                                            keyword2 = new TemplateDataItem(dataRow1["nodename"].ToString() + "出现问题需要管理者帮助,详细请询问员工。", "#e51d36"),
                                            keyword3 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd")),
                                            keyword4 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#000000"),
                                            keyword5 = new TemplateDataItem(dataRow1["nodename"].ToString(), "#000000"),
                                            remark = new TemplateDataItem("备注:" + VerificationOpinion, "#e51d36")
                                        };
                                        string templateid = NetWing.Common.ConfigHelper.GetValue("templageid");//从web.config 获得模板ID
                                                                                                               //通知所有员工就是openid不同
                                        string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(adataRow["OpenID"].ToString(), templateid, NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?keyid=" + data["keyid"].ToString() + "", templateData);
                                    }
                                    SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务

                                    JydflowRecordModel jydflowRecordModel = new JydflowRecordModel
                                    {
                                        processID = Convert.ToInt32(FlowInstanceId),
                                        Operationalcontent = dataRow1["nodename"].ToString(),
                                        Operationtime = DateTime.Now,
                                        addtime = dataRow1["timestamp"].ToString(),
                                        Operctionname = openidrow["UserName"].ToString(),
                                        orderid = dr2["orderid"].ToString(),
                                        Remarks = VerificationOpinion + "，原因:这里出了问题,等管理员处理。",
                                        nikeyid = int.Parse(row["orderkey"].ToString()),
                                        sortid = int.Parse(dataRow1["sortid"].ToString()),

                                    };
                                    DbUtils.tranInsert(jydflowRecordModel, tran);//提交流程操作记录
                                    tran.Commit();//提交事务
                                    context.Response.Write("{\"status\":\"1\",\"filename\":\"修改成功\"}");//修改成功
                                }
                            }
                            catch (Exception e)
                            {
                                context.Response.Write("{\"status\":\"2\",\"filename\":\"'" + e.Message + "'\"}");//发送微信出错
                                WriteLogs.WriteLogsE("Logs", "Error >> xiugai", e.Message + " >>> " + e.StackTrace);
                            }
                        }
                        else
                        {

                            context.Response.Write("{\"status\":\"3\",\"filename\":\"这个订单完成了\"}");
                        }
                    }
                    #endregion 
                    else //选择流程
                    {
                        bool bo = templateflow.username(VerificationOpinion, FlowInstanceId, VerificationFinally, sl, username, keyid);
                        if(bo == true)
                        {
                        context.Response.Write("{\"status\":\"1\",\"filename\":\"修改成功\"}");
                        }
                        else
                        {
                            context.Response.Write("{\"status\":\"2\",\"filename\":\"修改失败,联系管理员\"}");
                        }
                    }

                    break;
                #endregion

                #region 任务处理
                case "mobileViewFlow":
                    string oakeyid = context.Request["keyid"];//子订单ID


                    string myopenid = CookieHelper.GetCookie("useropenid");
                    string sql = "select top 1 * from jydOrderDetail where KeyId =" + oakeyid + "";
                    DataRow dr = SqlEasy.ExecuteDataRow(sql);
                    string sqli = "select * from jydflowtasklist where schemecontent='" + oakeyid + "'";
                    DataRow dataRow = SqlEasy.ExecuteDataRow(sqli);





                    if (int.Parse(dataRow["isitcomplete"].ToString()) != 0)
                    {
                        string sqldt = "select * from jydflowTasktemplate where Printedmattername = '" + dr["PrintType"].ToString() + "' and sortid='" + dataRow["isitcomplete"].ToString() + "'";

                        SqlDataReader dt = SqlEasy.ExecuteDataReader(sqldt);
                        JydflowtasklistModel fim = new JydflowtasklistModel();
                        while (dt.Read())
                        {
                            fim.InjectFrom<ReaderInjection>(dt);
                        }
                        context.Response.Write(JSONhelper.ToJson(fim));
                    }
                    else
                    {
                        context.Response.Write("{\"status\":\"1\",\"filename\":\"这订单完成了\"}");
                    }
                    break;
                #endregion

                #region 添加
                case "add":
                    context.Response.Write(JydflowtasklistBll.Instance.Add(rpm.Entity));
                    break;
                #endregion
                #region 修改
                case "edit":
                    JydflowtasklistModel d = new JydflowtasklistModel();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    context.Response.Write(JydflowtasklistBll.Instance.Update(d));
                    break;
                #endregion

                #region  导出
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(JydflowtasklistModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                #endregion

                #region 导入
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                #endregion

                #region 删除
                case "delete":
                    context.Response.Write(JydflowtasklistBll.Instance.Delete(rpm.KeyId));
                    break;
                #endregion


                #region 批量删除
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.JydflowtasklistDal.Instance.Delete(rpm.KeyIds));
                    break;
                #endregion

                #region 显示
                default:
                    context.Response.Write(JydflowtasklistBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
                    #endregion
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(JydflowtasklistModel));//数据库中的表名
                                                                                                     //自定义的datatable和数据库的字段进行对应  
                                                                                                     //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                                     //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}